package com.sskj.postar.service.impl;

import com.sskj.postar.core.config.ServiceException;
import com.sskj.postar.core.utils.ApplicationUtils;
import com.sskj.postar.enums.FabiTradeOrderStatusEnum;
import com.sskj.postar.model.FabiPublish;
import com.sskj.postar.model.FabiTrade;
import com.sskj.postar.model.User;
import com.sskj.postar.model.UserAsset;
import com.sskj.postar.service.FabiPublishService;
import com.sskj.postar.service.FabiService;
import com.sskj.postar.service.FabiTradeService;
import com.sskj.postar.service.UserAssetService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;

@Service
public class FabiServiceImpl implements FabiService {
    @Resource
    UserAssetService userAssetService;
    @Resource
    FabiTradeService fabiTradeService;
    @Resource
    FabiPublishService fabiPublishService;

    @Transactional(rollbackFor = {ServiceException.class})
    @Override
    public void tradeSell(BigDecimal numBig, UserAsset userAsset, FabiPublish fabiPublish, String num, String payType) {
        userAssetService.updateMoney(userAsset.getId(), "-" + numBig.toPlainString(), numBig.toPlainString());

        fabiPublishService.updateLeftNum(fabiPublish.getId(), "-" + num);
        FabiTrade fabiTrade = new FabiTrade();
        fabiTrade.setNum(num);
        fabiTrade.setBuyyerId(fabiPublish.getUserId());
        fabiTrade.setSellerId(userAsset.getUserId());
        fabiTrade.setPrice(fabiPublish.getPrice());
        fabiTrade.setPublishOrderId(fabiPublish.getId());
        fabiTrade.setSellerPayType(payType);
        fabiTrade.setStatus(FabiTradeOrderStatusEnum.WAIT_PAY.getCode());
        fabiTrade.setPayCode(ApplicationUtils.getNumStringRandom(6));
        fabiTrade.setTradeOrderId(ApplicationUtils.getUUID());
        fabiTradeService.insert(fabiTrade);
    }

    @Override
    public void tradeBuy(User user,FabiPublish fabiPublish, String num) {
        FabiTrade fabiTrade = new FabiTrade();
        fabiTrade.setNum(num);
        fabiTrade.setBuyyerId(user.getId());
        fabiTrade.setSellerId(fabiPublish.getUserId());
        fabiTrade.setPrice(fabiPublish.getPrice());
        fabiTrade.setPublishOrderId(fabiPublish.getId());
        fabiTrade.setStatus(FabiTradeOrderStatusEnum.WAIT_PAY.getCode());
        fabiTrade.setPayCode(ApplicationUtils.getNumStringRandom(6));
        fabiTrade.setTradeOrderId(ApplicationUtils.getUUID());
        fabiTradeService.insert(fabiTrade);
    }
}
